package com.relax.tcp.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.nio.charset.StandardCharsets;

public class MyTcpClinetHandler extends SimpleChannelInboundHandler<ByteBuf> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //todo 发送数据
        System.out.println("channelActive  通道建立");
//        final ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();
//        byteBuf.writeShort(4);
//        byteBuf.writeBytes(("aaaa").getBytes(StandardCharsets.UTF_8));
//        ctx.writeAndFlush(byteBuf);
//
//
//        final ByteBuf byteBuf2 = ByteBufAllocator.DEFAULT.buffer();
//        byteBuf2.writeShort(4);
//        byteBuf2.writeBytes(("bbbb").getBytes(StandardCharsets.UTF_8));
//        ctx.writeAndFlush(byteBuf2);

//        final ByteBuf byteBuf3 = ByteBufAllocator.DEFAULT.buffer();
//        byteBuf3.writeShort(4);
//        ctx.writeAndFlush(byteBuf3);
//
//        final ByteBuf byteBuf4 = ByteBufAllocator.DEFAULT.buffer();
//        byteBuf4.writeBytes(("cccc").getBytes(StandardCharsets.UTF_8));
//        ctx.writeAndFlush(byteBuf4);


        // 换行分隔符


        /**
         * 客户端写一个用户 com.relax.netty.tcp.decode.Person
         */
        final ByteBuf byteBuf4 = ByteBufAllocator.DEFAULT.buffer();
        byteBuf4.writeShort(9);
        byteBuf4.writeBytes(("彭青松").getBytes(StandardCharsets.UTF_8));

        ctx.writeAndFlush(byteBuf4);




    }

    public static void main(String[] args) {
        System.out.println("彭青松".getBytes().length);
    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        System.out.println(System.currentTimeMillis() + "==>channelRead0");
        short dataLength = msg.readShort();
        byte[] buffer = new byte[dataLength];
        msg.readBytes(buffer);
        String message = new String(buffer, CharsetUtil.UTF_8);
        System.out.println("client 接收消息,消息长度是" + dataLength+",消息内容是:"+message);

        ctx.pipeline().write(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println(System.currentTimeMillis() + "==>channelReadComplete");
        super.channelReadComplete(ctx);
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println(System.currentTimeMillis() + "==>channelRegistered");
        super.channelRegistered(ctx);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println(System.currentTimeMillis() + "==>channelUnregistered");
        super.channelUnregistered(ctx);
    }
}
